<!DOCTYPE HTML>
<html>
<head>
<title>test WebSocket</title>
</head>
<body>
  <input id="text" type="text" />
  <button onclick="send()">发送</button>
  <button onclick="closeWebSocket()">关闭</button>
  <div id="message"></div>
</body>
<script src="/jquery.js"></script>
<script type="text/javascript">
    var websocket = new WebSocket("ws://localhost:8080/test");
    //连接发生错误的回调方法
    websocket.onerror = function() {
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event) {
        setMessageInnerHTML("浏览器事件：连接成功!");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event) {
        setMessageInnerHTML("服务端回复-->" + event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function() {
        setMessageInnerHTML("浏览器事件：关闭连接！");
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = $('#text').val();
        setMessageInnerHTML("浏览器发送：" + message);
        websocket.send(message);
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        var htmlTxt = $('#message').html();
        $('#message').html(htmlTxt + '<br/>' + innerHTML + '<br/>');
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function() {
        websocket.close();
    }
</script>
</html>